package main

import "fmt"

/*
  1.向Slice添加元素
  arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
  s1 := arr[2:6]
  s2 := s1[3:5]
  s3 := append(s2, 10)
  s4 := append(s3, 11)
  s5 := append(s4, 12)
  s3,s4,s5的值为? arr的值为?
  (1) 添加元素时如果超越cap，系统会重新分配更大的底层数组
  (2) 由于值传递的关系，必须接收append的返回值
  (3) s = append(s, val)


*/
func main() {
	// 添加slice
	appendSlice()
	// 创建slice
	create()

}

func appendSlice() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5] // [5, 6]
	s3 := append(s2, 10)
	s4 := append(s3, 11)
	s5 := append(s4, 12)
	fmt.Println("s3, s4, s5", s3, s4, s5)
	// s4 and s5 no longer view arr.
	fmt.Println("arr =", arr)
}

func create() {
	fmt.Println("Creating slice")
	// 创建slice方法1
	var s []int // zero value for slice is nil

	for i := 0; i < 100; i++ {
		printSlice(s)
		s = append(s, 2*i+1)
	}
	fmt.Println(s)

	// 创建slice方法2
	s1 := []int{2, 4, 6, 8}
	printSlice(s1)

	// 创建slice方法3
	s2 := make([]int, 16)
	s3 := make([]int, 10, 32)
	printSlice(s2)
	printSlice(s3)

	fmt.Println("Copying slice")
	copy(s2, s1)
	printSlice(s2)

	fmt.Println("Deleting elements from slice")
	s2 = append(s2[:3], s2[4:]...)
	printSlice(s2)

	fmt.Println("Popping from front")
	front := s2[0]
	s2 = s2[1:]
	fmt.Println(front)
	printSlice(s2)

	fmt.Println("Popping from back")
	tail := s2[len(s2)-1]
	s2 = s2[:len(s2)-1]
	fmt.Println(tail)
	printSlice(s2)

}

func printSlice(s []int) {
	fmt.Printf("%v,len=%d, cap=%d\n", s, len(s), cap(s))
}
